package com_.dxy_test_.lock_;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description TODO
 * @Author dangxianyue
 * @Date 2023/6/20 17:07
 */
public class ReentrantLockTest {
    private static Random random = new Random();
    private static int count = 0;
    // 声明一个有10道锁的栅栏
    private static CyclicBarrier barrier = new CyclicBarrier(10);
    private static Lock lock = new ReentrantLock();

    private static void plus() throws Exception {
        lock.lock();
        try {
            for (int i = 0; i < 100; i++) {
                Thread.sleep(random.nextInt(20));// 模拟业务耗时
                count++;// 为啥每次进来都会强制从主内存读取？
            }
        } finally {
            lock.unlock();// 为啥每次出去都要刷新到主内存？
        }
    }

    public static class PlusThread extends Thread {
        @Override
        public void run() {
            try {
                barrier.await();
                plus();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        PlusThread t1 = new PlusThread();
        PlusThread t2 = new PlusThread();
        PlusThread t3 = new PlusThread();
        PlusThread t4 = new PlusThread();
        PlusThread t5 = new PlusThread();
        PlusThread t6 = new PlusThread();
        PlusThread t7 = new PlusThread();
        PlusThread t8 = new PlusThread();
        PlusThread t9 = new PlusThread();
        PlusThread t10 = new PlusThread();

        // 启动10个线程
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
        t7.start();
        t8.start();
        t9.start();
        t10.start();

        // 等待10个子线程执行完
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        t5.join();
        t6.join();
        t7.join();
        t8.join();
        t9.join();
        t10.join();

        System.out.println("count: " + count);
    }
}
